package com.zhentao.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.file.service.impl.FileStorageServiceImpl;
import com.zhentao.mapper.ApArticleContentMapper;
import com.zhentao.mapper.ArticleMapper;
import com.zhentao.model.article.pojo.ApArticle;
import com.zhentao.model.article.pojo.ApArticleContent;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.service.ApArticleContentService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @Date 2024/5/9 15:15
 * @Author xdm
 **/
@Service
public class ApArticleContentServiceImpl implements ApArticleContentService {

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageServiceImpl fileStorageService;
    @Autowired
    private ArticleMapper articleMapper;
    @Async//开启异步处理
    @SneakyThrows
    @Override
    public ResponseResult createStaticUrl(Long articleId) {
        //根据iD生成html静态文件，然后文件上传到minio里面
        //1.根据id获取文章内容
        QueryWrapper<ApArticleContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ApArticleContent::getArticleId, articleId);

        ApArticleContent apArticleContent = apArticleContentMapper.selectOne(queryWrapper);

        if (apArticleContent != null) {
            //2.把内容通过freemarker生产html文件
            Template template = configuration.getTemplate("article(1).ftl");

            Map<String, Object> map = new HashMap<>();
            String content = apArticleContent.getContent();
            map.put("content", JSONArray.parseArray(content));

            StringWriter out = new StringWriter();
            template.process(map, out);

            //3.把html上传到minio里面

            InputStream inputStream = new ByteArrayInputStream(out.toString().getBytes(StandardCharsets.UTF_8));
            String url = fileStorageService.uploadHtmlFile(apArticleContent.getArticleId() + ".html", inputStream);

            //4.修改ap_article表里面的static_url字段
            ApArticle apArticle=new ApArticle();
            apArticle.setId(articleId);
            apArticle.setStaticUrl(url);
            articleMapper.updateById(apArticle);

            return ResponseResult.okResult(200,url);
        }


        return ResponseResult.errorResult(201,"文章不存在");
    }
}